package com.service.single.util;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author: 一休
 * @DateTime: 2023/9/12 17:11
 */
public class CnblogsStar {

    private final String cookie = ".Cnblogs.AspNetCore.Cookies=CfDJ8DfB03_iObVLoqH7ndAeeDjnVHY-99DE9LGHZN0U3tnxTv0naRYWDWnydhmQQn78d9aINmvyfs8jqtzFwygj7ElMiJUgka3KSjAReedio6U9YUL2wPHp3cpxjCK9vZciNBJ5XKu8i5duYuU-69Xh9T7dM6aMRvbdbYaha-09KbPQC7B6xnz3E1MfyFgSeUQR8aPzWdiONuk8b7hK9KtdhKIB6GkgySqWra8etYbYe7e6uiS2bW1-RXQgftohPmimgrmTy24bQnt67rHn_7e9oHT_G9QJqKuHN7Q_p6ylXE-g2js3kFNulKGtxgXzhUKpSP8eOVosOHO3kw5Lvq-lKFmaDRygqZr3YlXFtf0DAkmyrU83jjji5FCZMEVtG8e_75TzFqmsRu-CGY5qGzD0PRZZVjQVjBRS8PkHI0hLBheD8GRAHyyXKMsbTtGj2CiJt2c3UbDU9Kpb1KWIw_hVeN1O5M5PzvF1oZ6vBd5seOimsTPprzI65wNlLpEu2HDozI17jhnP6-VCtAn3eypVSZB4woAVpDFJVZNF_RHeMQ-k4BXRwrj_6nbJivkUzYNqochglW6QKJpCo3YuZ9NXD2hfm9_lM47EfuzpoiUqCf_v";
    private final String requestWith = "XMLHttpRequest";

    public CnblogsStar() {
    }

    public CnblogsStar(String content) {
        this.publish(content);
    }

    public CnblogsStar(List<String> list) {
        if (CollectionUtils.isNotEmpty(list)) {
            for (String s : list) {
                this.publish(s);
            }
        }
    }


    /**
     * 删除指定的星星
     *
     * @param ingId 要删除的星星的ID
     *              该ID用于标识特定的星星资源，是删除操作的关键参数。
     */
    public void del(String ingId) {
        // 构建删除请求的URL
        String delUrl = "https://ing.cnblogs.com/ajax/ing/del";
        // 发送POST请求，提交删除表单，包含ingId参数，并设置请求头信息
        String delBody = HttpRequest.post(delUrl).form("ingId", ingId).header("cookie", cookie).header("x-requested-with", requestWith).execute().body();
        // 打印删除操作的响应内容
        System.out.println("删除：" + delBody);
    }


    /**
     * 发布星星
     * <p>
     * 向指定URL发布内容，并检查发布的内容是否包含星星。
     *
     * @param content 要发布的内容
     */
    private void publish(String content) {
        // 构建发布请求的URL和请求体
        String publishUrl = "https://ing.cnblogs.com/ajax/ing/Publish";
        String publishBody = HttpRequest.post(publishUrl).form("content", content).form("publicFlag", 1)
                .header("cookie", cookie).execute().body();
        // 打印发布结果
        System.out.println("发布：" + publishBody);
        // 检查发布的内容中是否包含星星
        checkStar(content);
    }


    /**
     * 校验网络上的图片是否包含星星，如果不包含则删除该图片，并发布新内容。
     * <p>
     * 参数:
     * content - 要发布的新内容。
     * <p>
     * 返回值: 无
     */
    public void checkStar(String content) {
        // 构造请求URL并发送GET请求，获取网页内容
        String requestUrl = "https://ing.cnblogs.com/ajax/ing/GetIngList?IngListType=My&PageIndex=1&PageSize=30&Tag=&_=1685670088011";
        String body = HttpRequest.get(requestUrl).header("Content-Type", "application/json")
                .header("Accept-Encoding", "gzip, deflate, br")
                .header("Connection", "keep-alive")
                .header("cookie", cookie)
                .header("accept", "text/plain, */*; q=0.01")
                .header("x-requested-with", requestWith).execute().body();
        // 使用Jsoup解析获取到的HTML内容
        Document document = Jsoup.parse(body);
        Elements elementLis = document.getElementsByTag("li");
        Element elementLi = elementLis.get(0);
        Elements divFeedBody = elementLi.select("div[class=feed_body]");
        Element feedBody = divFeedBody.get(0);
        Elements imgs = feedBody.getElementsByTag("img");
        Element img = imgs.get(0);
        // 打印图片信息并提取标题
        System.out.println("img: " + img.toString());
        String title = img.attr("title");
        // 检查标题中是否包含特定关键词，不包含则删除图片并发布新内容
        if (StringUtils.isNotBlank(title)) {
            boolean contains = title.contains("星") || title.contains("庆祝");
            if (!contains) {
                String id = feedBody.attr("id");
                String[] array = id.split("_");
                String value = array[2];
                System.out.println("删除：" + value);
                this.del(value);
                try {
                    Thread.sleep(300000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                this.publish(content);
            }
            // 打印星星检查结果
            System.out.println("星星：" + content + " " + img + " " + LocalDateTime.now());
        }
    }


    public static void main(String[] args) throws Exception {
//        String url = "https://www.toutiao.com/hot-event/hot-board/?origin=toutiao_pc&_signature=_02B4Z6wo00101r.r7TAAAIDB7RTNKwXFep6.z-mAAMmNEIL21bHsc2DytviNK6DWjHhQrROlIboL0uY16O3wvohrSV-1zPe08jGejq73A2XdFO.a2BL0tFZ06e9Zezu9.4yT.mmqjcpaVkKQ7c";
//        String body = HttpRequest.get(url).execute().body();
//        JSONObject result = JSONObject.parseObject(body);
//        JSONArray array = result.getJSONArray("data");
//        array.forEach(item -> {
//            JSONObject jsonObject = (JSONObject) item;
//            String title = jsonObject.getString("Title");
//            String link = jsonObject.getString("Url");
//            new CnblogsStar("[新闻]"+title + link);
//        });

        new CnblogsStar("[BIG胆]上帝为你关上一道门的同时，还会顺带夹你的脑子。");

    }
}
